package com.utils.ylt;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.security.MessageDigest;

/**
 * @author zhouliang
 * @create 2018-12-06 15:28
 */
public class YltUtils {

    private static char[] hexDigits = new char[]{'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd',
            'e', 'f'};

    public static String md5Digest(String s) throws Exception {
        try {
            byte[] e = s.getBytes("UTF-8");
            MessageDigest mdTemp = MessageDigest.getInstance("MD5");
            mdTemp.update(e);
            byte[] md = mdTemp.digest();
            int j = md.length;
            char[] str = new char[j * 2];
            int k = 0;

            for (int i = 0; i < j; ++i) {
                byte byte0 = md[i];
                str[k++] = hexDigits[byte0 >>> 4 & 15];
                str[k++] = hexDigits[byte0 & 15];
            }

            return new String(str);
        } catch (Exception arg8) {
            return null;
        }
    }

    /**
     *  获取微信价格
     * 原始价格为单位为元，微信单位为分，所以需要转换
     * @param
     * @return
     */
    public static String YuanTofen(String price) {
        BigDecimal sourcePrice = new BigDecimal(price);//原始价格 单位元
        BigDecimal b2 = new BigDecimal("100");//将元换算为分的单位 100
        String tfee=Double.toString(sourcePrice.multiply(b2).doubleValue());
        // 订单金额
        String total_fee = tfee.substring(0, tfee.indexOf("."));
        return total_fee;
    }

    /**
     * 将分转换为元 如：1 分= 0.01元
     * @param price
     * @return
     */
    public static String fenToYuan(String price){
        BigDecimal sourcePrice = new BigDecimal(price);//原始价格 单位元
        BigDecimal b2 = new BigDecimal("100");//将元换算为分的单位 100
        String tfee=Double.toString(sourcePrice.divide(b2).doubleValue());
        // 订单金额
        return tfee;
    }

    /**
     * 用户端实际ip
     */
    public static String getIpAddr(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }

}
